import 'package:merchants/models/merchant_user.dart';
import 'package:merchants/services/base-service.dart';

class MerchantUserService extends BaseService {
  MerchantUserService({required super.ref});

  // 获取员工列表，可按状态过滤（pending、approved）
  Future<List<MerchantUser>> getStaffList({
    String? status,
    String? merchantId,
  }) async {
    try {
      final Map<String, dynamic> where = {};
      if (status != null && status.isNotEmpty) {
        where['status'] = {'\$eq': status};
      }
      if (merchantId != null && merchantId.isNotEmpty) {
        where['merchant_id'] = {'\$eq': merchantId};
      }

      final response = await post<Map<String, dynamic>>(
        '/admin/merchant-user/get-list',
        body:
            where.isNotEmpty
                ? {
                  'filter': {'where': where},
                }
                : null,
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '获取员工列表失败');
          }
          return json;
        },
        requireToken: true,
      );

      final List<dynamic> records =
          response['data']['records'] as List<dynamic>;
      return records
          .map((json) => MerchantUser.fromJson(json as Map<String, dynamic>))
          .toList();
    } catch (e) {
      throw ApiException('获取员工列表失败: $e');
    }
  }

  // 通过员工加入申请
  Future<void> approveStaff(String staffId) async {
    try {
      final response = await post<Map<String, dynamic>>(
        '/merchant-user/approve',
        body: {'id': staffId, 'status': 'approved'},
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '通过申请失败');
          }
          return json;
        },
        requireToken: true,
      );

      if (response['data'] == null) {
        throw ApiException('通过申请失败：无返回数据');
      }
    } catch (e) {
      throw ApiException('通过员工申请失败: $e');
    }
  }

  // 获取单个员工详情
  Future<MerchantUser> getStaffById(String staffId) async {
    try {
      final response = await post<Map<String, dynamic>>(
        '/merchant-user/get',
        body: {
          'filter': {
            'where': {
              'id': {'\$eq': staffId},
            },
          },
        },
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '查询员工失败');
          }
          return json;
        },
        requireToken: true,
      );

      if (response['data'] != null) {
        return MerchantUser.fromJson(response['data'] as Map<String, dynamic>);
      } else {
        throw ApiException('员工未找到');
      }
    } catch (e) {
      throw ApiException('获取员工详情失败: $e');
    }
  }

  Future<void> uploadPushToken({
    required String token,
    required String brand,
    required String unionid,
  }) async {
    try {
      final response = await post<Map<String, dynamic>>(
        '/merchant-user/push/register', // Adjust endpoint as per your API
        body: {'type': brand, 'token': token, 'unionid': unionid},
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '上传推送 token 失败');
          }
          return json;
        },
      );

      if (response['data'] == null) {
        throw ApiException('上传推送 token 失败：无返回数据');
      }
    } catch (e) {
      throw ApiException('上传推送 token 失败: $e');
    }
  }

  /// 员工首次登录，补全个人资料
  Future<void> updateMyProfile({required String name}) async {
    await put('/merchant-users/me/profile',
        body: {'name': name},
        parser: (json) {});
  }
}
